package org.yunai.yfserver.command;

import org.slf4j.Logger;
import org.yunai.yfserver.common.LoggerFactory;

import java.util.*;

/**
 * 消息管理器<br />
 * 用于消息编号获得其命令，不负责分发命令。
 * User: yunai
 * Date: 13-3-26
 * Time: 上午9:30
 */
public class MessageDispatcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.msg, MessageDispatcher.class);

    private static final MessageDispatcher INSTANCE = new MessageDispatcher();

    /**
     * 消息编号与命令集合<br />
     * <K, V>对应<消息编号, 命令列表><br />
     * 一个消息编号可以对应多个命令
     */
    private final Map<Short, List<Command>> commands = new HashMap<Short, List<Command>>();

    public static MessageDispatcher getInstance() {
        return INSTANCE;
    }

    /**
     * 注册命令
     *
     * @param command 命令
     */
    public void register(Command command) {
        Short code = command.getCode();
        List<Command> commandItems = commands.get(code);
        if (commandItems == null) {
            commands.put(code, commandItems = new ArrayList<Command>());
        }
        // 校验是否存在该命令
        if (commands.size() > 0) {
            for (Command commandItem : commandItems) {
                if (commandItem.getClass().equals(command.getClass())) {
                    return;
                }
            }
        }
        // 加入
        commandItems.add(command);

        LOGGER.debug("[add] [add code:{} with command:{}].", code, command.getClass());
    }

    public List<Command> getCommands(Short code) {
        List<Command> commandItems = commands.get(code);
        if (commandItems == null) {
            LOGGER.warn("[getCommands] [coed:{} has no commands].", code);
            return Collections.emptyList();
        }
        return commandItems;
    }
}